package org.wedding.center.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang.StringUtils;
import org.wedding.center.dto.query.OrderQuery;
import org.wedding.center.entity.*;
import org.wedding.center.mapper.OrderInfoMapper;
import org.wedding.center.mapper.ProductInfoMapper;
import org.wedding.center.mapper.ServiceInfoMapper;
import org.wedding.center.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.wedding.center.util.RedemptionCodeGenerator;
import org.wedding.enums.system.ResultCodeEnum;
import org.wedding.system.entity.UserInfo;
import org.wedding.system.mapper.UserMapper;
import org.wedding.utils.CommonResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.ObjectUtil;
import org.wedding.dto.PageModel;
import org.wedding.utils.PageUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 订单信息表(OrderInfo)表服务实现类
 *
 * @author songkaiyue
 * @since 2025-05-19 17:26:19
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private AmountInfoService amountInfoService;
    @Resource
    private CouponInfoService couponInfoService;
    @Resource
    private NoticeInfoService noticeInfoService;
    @Resource
    private ServiceInfoMapper serviceInfoMapper;
    @Resource
    private ProductInfoMapper productInfoMapper;
    @Resource
    private UserMapper userMapper;

    /**
     * 分页查询所有数据
     *
     * @return
     */
    @Override
    public CommonResult<PageModel> findAll(OrderQuery query) {
        try {
            String userId = StpUtil.getSession().get("userId").toString();
            String role = StpUtil.getSession().get("role").toString();
            if ("0".equals(role)) {
                //若是用户则查询自己的订单
                query.setUserId(userId);
            } else if ("1".equals(role)) {
                //若是商家则查询自己的订单
                query.setMerchantId(userId);
            }
            List<OrderInfo> list = baseMapper.selectAll(query);
            List<OrderInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }

    }

    @Override
    public CommonResult<PageModel> findAllUser(OrderQuery query) {
        try {
            String userId = StpUtil.getSession().get("userId").toString();
            String role = StpUtil.getSession().get("role").toString();
                //若是用户则查询自己的订单
            query.setUserId(userId);
            List<OrderInfo> list = baseMapper.selectAll(query);
            List<OrderInfo> setList = query.setList(PageUtil.getListPage(query.getCurrent(), query.getPageSize(), list), list.size());
            query.setList(setList, list.size());
            return CommonResult.success(query);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }

    }

    /**
     * 根据id查看详情
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult<OrderInfo> view(String id) {
        try {
            OrderInfo orderInfo = baseMapper.findById(id);
            if ("1".equals(orderInfo.getType())) {
                //商品订单
                ProductInfo productInfo = productInfoMapper.findById(orderInfo.getProductId());
                if (ObjectUtil.isNotEmpty(productInfo)) {
                    orderInfo.setSelfPickup(productInfo.getSelfPickup());
                    orderInfo.setProPhone(productInfo.getPhone());
                    orderInfo.setOldAomunt(productInfo.getOldAmount());
                }
            }
            return CommonResult.success(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 根据核销码查询
     *
     * @param redeemCode
     * @return
     */
    @Override
    public CommonResult<OrderInfo> findByRedeemCode(String redeemCode) {
        try {
            OrderInfo orderInfo = baseMapper.findByRedeemCode(redeemCode);
            return CommonResult.success(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }


    /**
     * 新增数据
     *
     * @param orderInfo
     * @return
     */
    @Override
    public CommonResult add(OrderInfo orderInfo) {
        try {
            if (ObjectUtil.isEmpty(orderInfo.getOrderAmount())) {
                return CommonResult.failed("订单金额不能为空！");
            }
            orderInfo.setId(IdUtil.simpleUUID());
            orderInfo.setCreateTime(DateUtil.now());
            orderInfo.setDelFlag("0");
            if (StrUtil.isEmpty(orderInfo.getStatus())) {
                orderInfo.setStatus("0");
            }
            //生成订单号
            String code = RedemptionCodeGenerator.getCode();
            orderInfo.setCode(code);
            //生成尾款订单号
            String wkcode = RedemptionCodeGenerator.getWkCode();
            orderInfo.setWkcode(wkcode);
            List<String> codes = baseMapper.findRedeemCodes();
            //生成兑换码
            String redeemCode = RedemptionCodeGenerator.generate(codes);
            orderInfo.setRedeemCode(redeemCode);
            //默认付款方式为微信支付
            if (StrUtil.isEmpty(orderInfo.getPayType())) {
                orderInfo.setPayType("0");
            }
            orderInfo.setPayStatus("0");
            orderInfo.setFinalStatus("0");
            //订单金额
            BigDecimal orderAmount = orderInfo.getOrderAmount();
            //使用优惠券
            if (StrUtil.isNotEmpty(orderInfo.getCouponId())) {
                //使用优惠券
                CommonResult<CouponInfo> result = couponInfoService.useCoupon(orderInfo);
                if (result.getCode() != 0) {
                    return result;
                }
                //使用优惠券后计算金额
                CouponInfo couponInfo = result.getData();
                if ("0".equals(couponInfo.getStatus())) {
                    BigDecimal amount = orderAmount.subtract(couponInfo.getAmount());
                    orderInfo.setAmount(amount);
                }
            }
            //是否 定金
            if (StrUtil.isNotEmpty(orderInfo.getPayDeposit()) && "0".equals(orderInfo.getPayDeposit())) {
                //定金金额-定金固定总价的20% 这里
                BigDecimal depositAmount = orderAmount.multiply(new BigDecimal("0.2"));
                orderInfo.setAmount(depositAmount);
                //尾款金额
                BigDecimal finalAmount = orderAmount.subtract(depositAmount);
                orderInfo.setFinalAmount(finalAmount);
                orderInfo.setIsDeposit("0");
            } else {
                //全款
                orderInfo.setIsDeposit("1");
                orderInfo.setAmount(orderAmount);
            }
            orderInfo.setUserId(StpUtil.getLoginIdAsString());
            if (StrUtil.isNotEmpty(orderInfo.getType())) {
                if ("0".equals(orderInfo.getType())) {
                    //服务订单
                    ServiceInfo serviceInfo = serviceInfoMapper.findById(orderInfo.getProductId());
                    if (ObjectUtil.isNotEmpty(serviceInfo)) {
                        orderInfo.setImgUrl(serviceInfo.getImgUrl());
                        orderInfo.setName(serviceInfo.getName());
                        UserInfo userInfo = userMapper.findById(serviceInfo.getUserId());
                        if (ObjectUtil.isNotEmpty(userInfo)) {
                            orderInfo.setMerchantId(userInfo.getId());
                            orderInfo.setMerchantName(userInfo.getMerchantName());
                            orderInfo.setIconUrl(userInfo.getIconUrl());
                        }
                    }
                } else if ("1".equals(orderInfo.getType())) {
                    //商品订单
                    ProductInfo productInfo = productInfoMapper.findById(orderInfo.getProductId());
                    if (ObjectUtil.isNotEmpty(productInfo)) {
                        orderInfo.setImgUrl(productInfo.getImgUrl());
                        orderInfo.setName(productInfo.getProName());
                        UserInfo userInfo = userMapper.findById(productInfo.getUserId());
                        if (ObjectUtil.isNotEmpty(userInfo)) {
                            orderInfo.setMerchantId(userInfo.getId());
                            orderInfo.setMerchantName(userInfo.getMerchantName());
                            orderInfo.setIconUrl(userInfo.getIconUrl());
                        }
                    }
                }
            }
            baseMapper.insert(orderInfo);
            if (StrUtil.isNotEmpty(orderInfo.getStatus()) && "5".equals(orderInfo.getStatus())) {
                //预约单通知-通知用户及商家
                if (StrUtil.isEmpty(orderInfo.getProductId())) {
                    return CommonResult.failed("预约单请选择服务！");
                }
                ServiceInfo serviceInfo = serviceInfoMapper.selectById(orderInfo.getProductId());
                if (ObjectUtil.isEmpty(serviceInfo)) {
                    return CommonResult.failed("预约单请选择服务！");
                }
                //通知用户
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(orderInfo.getUserId())
                        .notice("您已预约成功！")
                        .type("3")
                        .creator(StpUtil.getLoginIdAsString())
                        .build());
                //通知商家
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(serviceInfo.getUserId())
                        .notice("用户" + orderInfo.getContact() + "已成功预约您的服务,联系方式为" + orderInfo.getContact() + ",请及时处理！")
                        .type("3")
                        .creator(StpUtil.getLoginIdAsString())
                        .build());
            } else {
                //下单通知
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(orderInfo.getUserId())
                        .notice("您已成功下单！")
                        .type("3")
                        .creator(StpUtil.getLoginIdAsString())
                        .build());
            }
            return CommonResult.success(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            if(!StringUtils.isEmpty(e.getMessage())){
                boolean istrre = e.getMessage().contains("Token无效");
                if(istrre){
                    return CommonResult.failed(ResultCodeEnum.TOKEN_ERROR);
                }
            }
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 修改数据
     *
     * @param orderInfo
     * @return
     */
    @Override
    public CommonResult updateEntity(OrderInfo orderInfo) {
        try {
            //使用优惠券
            if (StrUtil.isNotEmpty(orderInfo.getCouponId())) {
                //使用优惠券
                CommonResult<CouponInfo> result = couponInfoService.useCoupon(orderInfo);
                if (result.getCode() != 0) {
                    return result;
                }
                //使用优惠券后计算金额
                CouponInfo couponInfo = result.getData();
                if ("0".equals(couponInfo.getStatus())) {
                    BigDecimal amount = orderInfo.getOrderAmount().subtract(couponInfo.getAmount());
                    orderInfo.setAmount(amount);
                }
            }
            orderInfo.setUpdateTime(DateUtil.now());
            baseMapper.updateById(orderInfo);
            //订单状态更新通知
            if (StrUtil.isNotEmpty(orderInfo.getStatus()) && !"0".equals(orderInfo.getStatus())) {
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(orderInfo.getUserId())
                        .notice("您的订单状态已更新,请及时查看！")
                        .type("3")
                        .creator(StpUtil.getLoginIdAsString())
                        .build());
            }
            return CommonResult.success(orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    /**
     * 删除数据
     *
     * @param ids
     * @return
     */
    @Override
    public CommonResult delete(List<String> ids) {
        try {
            if (ObjectUtil.isEmpty(ids)) {
                return CommonResult.failed(ResultCodeEnum.PARAM_ERROR);
            }
            for (String id : ids) {
                baseMapper.upDeleteById(id);
            }
            return CommonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }


    @Resource
    private RightInfoService rightInfoService;

    /**
     * 核销订单
     *
     * @param redeemCode
     * @return
     */
    @Override
    public CommonResult redeem(String redeemCode) {
        try {
            if (StrUtil.isEmpty(redeemCode)) {
                return CommonResult.failed("核销码不能为空！");
            }
            OrderInfo order = baseMapper.findByRedeemCode(redeemCode);
            //获取当前用户的角色
            //0:普通用户  1: 商家  2:管理员 3超级管理员
            String role = StpUtil.getSession().get("role").toString();

            RightInfo rightInfo = rightInfoService.findOne().getData();
            String commission = rightInfo.getCommission();
            BigDecimal commissionAmount = new BigDecimal(1).subtract( BigDecimal.valueOf(Double.parseDouble(commission)));


            System.out.println("当前用户的角色"+role);
            System.out.println("当前用户的角色11111111"+StpUtil.getSession());
            if (ObjectUtil.isNotEmpty(order)) {
                if ("1".equals(role)) {
                    //若是商家则查询自己的订单
                    // 判断是否是自己商家的
                    String merchantId = order.getMerchantId();
                    if (!merchantId.equals(StpUtil.getLoginId())) {
                        return CommonResult.failed("您没有权限核销此订单！");
                    }
                }
                if (StrUtil.isNotEmpty(order.getPayStatus()) && "1".equals(order.getPayStatus())) {
                    order.setStatus("2");
                    baseMapper.updateById(order);
                    CommonResult commonResult = amountInfoService.add(AmountInfo.builder()
                            .userId(order.getMerchantId())
                            .userName(order.getMerchantName())
                            .changeAmount(order.getAmount().multiply(commissionAmount))
                            .changeType("0")
                            .changeDetails("核销订单，全款到商家余额")
                            .cashStatus("1")
                            .build());
                    if (commonResult.getCode() != 0) {
                        return commonResult;
                    }
                    //核销通知-商家
                    noticeInfoService.add(NoticeInfo.builder()
                            .userId(order.getMerchantId())
                            .userName(order.getMerchantName())
                            .notice("您的订单已完成，请及时查看！")
                            .type("3")
                            .creator(StpUtil.getLoginIdAsString())
                            .build());
                    return CommonResult.success("核销成功！");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return CommonResult.failed("核销失败！");
    }

    /**
     * 获取预约时间
     *
     * @param type 0下单预约日期  1酒店预约时间
     * @return
     */
    @Override
    public CommonResult<List<String>> getAppointment(String type) {
        try {
            String userId = StpUtil.getSession().get("userId").toString();
            List<String> list;
            if ("0".equals(type)) {
                list = baseMapper.getAgreementTime(userId);
            } else {
                list = baseMapper.getSubscribeTime(userId);
            }
            return CommonResult.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }

    @Override
    public OrderInfo findByCode(String code) {
        return baseMapper.findByCode(code);
    }

    /**
     * 更新订单状态
     * @param orderNo
     * @param status
     */
    @Override
    public void updateOrderStatus(String orderNo, String status) {
        baseMapper.updateOrderStatus(orderNo, status);
    }




    /**
     * 订单付款回调
     *
     * @param code
     * @param payStatus 付款状态 0：待支付 1：已支付 2：已取消
     * @param isDeposit false：全款支付 true：尾款支付
     * @return
     */
    @Override
    public CommonResult<OrderInfo> payStatus(String code, String payStatus,boolean isDeposit) {
        try {
            OrderInfo order = baseMapper.findByCode(code);
            if (ObjectUtil.isEmpty(order)) {
                throw new RuntimeException("订单不存在！");
            }
            String userId = order.getUserId();
            if(isDeposit){

                order.setFinalStatus(payStatus);
                RightInfo rightInfo = rightInfoService.findOne().getData();
                String commission = rightInfo.getCommission();
                BigDecimal commissionAmount = new BigDecimal(1).subtract( BigDecimal.valueOf(Double.parseDouble(commission)));

             if("3".equals(payStatus)){
                 // 取消定金
                 //订单金额到商户余额
                 CommonResult commonResult = amountInfoService.add(AmountInfo.builder()
                         .userId(order.getMerchantId())
                         .userName(order.getMerchantName())
                         .changeAmount(order.getAmount().multiply(commissionAmount))
                         .changeType("0")
                         .changeDetails("订单取消，定金到商家余额")
                         .cashStatus("1")
                         .build());
                 if (commonResult.getCode() != 0) {
                     return commonResult;
                 }

             }else{
                 //订单金额到商户余额
                 CommonResult commonResult = amountInfoService.add(AmountInfo.builder()
                         .userId(order.getMerchantId())
                         .userName(order.getMerchantName())
                         .changeAmount(order.getOrderAmount().multiply(commissionAmount))
                         .changeType("0")
                         .changeDetails("订单完成，全款到商家余额")
                         .cashStatus("1")
                         .build());
                 if (commonResult.getCode() != 0) {
                     return commonResult;
                 }
             }

            }else {
                order.setPayStatus(payStatus);
            }
            if ("1".equals(order.getPayType())) {
                //余额支付
                AmountInfo amountInfo = new AmountInfo();
                amountInfo.setUserId(order.getUserId());
                amountInfo.setAmount(order.getAmount());
                amountInfo.setChangeType("1");
                amountInfo.setChangeDetails("订单支付");
                CommonResult commonResult = amountInfoService.add(amountInfo);
                if (commonResult.getCode() != 0) {
                    return commonResult;
                }
            }
            if ("1".equals(payStatus)  &&  !isDeposit) {
                //支付成功
                order.setStatus("1");
                //支付成功通知
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(order.getUserId())
                        .notice("您已成功支付，订单状态已更新,请及时查看！")
                        .type("3")
                        .creator(userId)
                        .build());
            } else if ("1".equals(payStatus) && isDeposit) {
                // 付尾款的直接付款后 完成
                order.setStatus("2");
                //支付成功通知
                noticeInfoService.add(NoticeInfo.builder()
                        .userId(order.getUserId())
                        .notice("您已成功支付，订单状态已更新,请及时查看！")
                        .type("3")
                        .creator(userId)
                        .build());
            }



            baseMapper.updateById(order);
            return CommonResult.success(order);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed(ResultCodeEnum.API_ERROR);
        }
    }


}
